package br.unisinos.aidk.puzzle;

import java.util.Random;

public class EightBoard implements Comparable<EightBoard>{

	public int[][] board = new int[3][3];

	public EightBoard() {
		byte cont = 0;
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				board[i][j] = cont++;
			}
		}
		shuffle();
	}

	public EightBoard(int[][] b) {
		board = b;
	}

	public EightBoard copy() {
		int[][] tmp = new int[3][3];
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				tmp[i][j] = board[i][j];
			}
		}
		EightBoard c = new EightBoard(tmp);
		return c;
	}

	public void move(int io, int jo, int it, int jt) {
		board[it][jt] = board[io][jo];
		board[io][jo] = 0;
	}

	public void shuffle() {
		int i, j, i2, j2, tmp;
		Random rand = new Random();
		for (int n = 0; n < 1000; n++) {
			i = rand.nextInt(3);
			j = rand.nextInt(3);
			i2 = rand.nextInt(3);
			j2 = rand.nextInt(3);
			tmp = board[i][j];
			board[i][j] = board[i2][j2];
			board[i2][j2] = tmp;
		}
	}

	public boolean isEmpty(int i, int j) {		
		return board[i][j] == 0;
	}

	public String toString() {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				buf.append(board[i][j] + " ");
			}
			buf.append("\n");
		}
		return buf.toString();
	}

	public boolean equals(Object target) {
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[i].length; j++) {
				if (board[i][j] != ((EightBoard) target).board[i][j]) {
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public int compareTo(EightBoard o) {
		float v1 = EightBoardProblem.evaluate(this);
		float v2 = EightBoardProblem.evaluate(o);
		if(v1<v2) return -1;
		else if(v1==v2) return 0;
		else return 1;
	}
}
